using System.ComponentModel.DataAnnotations;
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;

namespace MalwareMultiScan.Api.Attributes
{
    /// <summary>
    /// Validate uploaded file size for the max file size defined in settings.
    /// </summary>
    public class MaxFileSizeAttribute : ValidationAttribute
    {
        /// <inheritdoc />
        protected override ValidationResult IsValid(object value, ValidationContext validationContext)
        {
            var maxSize = validationContext
                .GetRequiredService<IConfiguration>()
                .GetValue<long>("MaxFileSize");

            var formFile = (IFormFile) value;

            if (formFile == null || formFile.Length > maxSize)
                return new ValidationResult($"File exceeds the maximum size of {maxSize} bytes");

            return ValidationResult.Success;
        }
    }
}